/**
 * Created by no1 on 2015/8/28.
 */
'use strict';
var mysql = require('../mysql.js');
var C = require('../../config/index');
var F = require('../../common/function');
var MPosts = require('../../model/posts.js');
var MTags = require('../../model/tags.js');
var MUser = require('../../model/users.js');
var Mman = require('../../common/man.js');
var imgRule = require('../../common/imgRule.js');
var _ = require('underscore');
var _s = require('underscore.string');
var md5 = require('md5');
var request = require('koa-request');
var async_request = require('request');
var logstash = require('./../logFlow/logstash.js');
_.v = require('validator');

/*
 *@todo  API14 点赞或取消点赞某主题
 * */
exports.like = function*(Env, data) {
  var fields;
  var loginStatus;
  if (!data) {
    fields = Env.I;
    //loginStatus = yield F.isLogin(Env);
    loginStatus = Env.I.loginStatus;
  }
  else {
    fields = data.fields;
    loginStatus = data.isLogin;
  }

  if (!loginStatus.status) {
    return F.returnMsg(401, '登录用户才能点赞', 3);
  }

  var act = fields.act; // 1/11:点赞 2/12:取消点赞,3回帖点赞，13取消回帖点赞
  var tid = fields.tid;
  var pid = fields.pid;
  var first = 0;
  if(act==3){
    if(pid==undefined || !_.v.isInt(pid)){
      return F.returnMsg(300, '回帖id输入有误', 3);
    }
  }

if(_.v.isIn(parseInt(act),[1,2,11,12])){
  if (tid) {
    var threadData = yield mysql.queryOne('select pid from mh_thread where tid=?', [tid]);
    if (threadData) {
      pid = threadData['pid'];
      first = 1;
    }
    else {
      return F.returnMsg(300, '帖子不存在', 3);
    }
  }
  else if (pid) {
    var postData = yield mysql.queryOne('select tid from mh_post where pid=?', [pid]);
    if (postData['tid']) {
      var threadData = yield mysql.queryOne('select pid from mh_thread where tid=?', [postData['tid']]);
      if (threadData['pid'] == pid) {
        first = 1;
      }
      tid = postData['tid'];
    }
    else {
      return F.returnMsg(300, '帖子不存在', 3);
    }
  }
  else {
    return F.returnMsg(300, '帖子不存在', 3);
  }
}

  //通过传递pid或pid,tid判断回帖是否存在，存在获取tid,pid,first;
  if(_.v.isIn(parseInt(act),[3,13])){
    //检查是否为回帖
    if(pid){
      if(tid){
        var post =yield mysql.query('SELECT pid,tid,uid FROM mh_post WHERE  pid=? AND tid=? and first=0',[pid,tid]);
      }else{
        var post =yield mysql.query('SELECT pid,tid,uid FROM mh_post WHERE  pid=? and first=0',[pid]);
      }
      if(post.length==0){
        return F.returnMsg(300, '回帖不存在', 3);
      }
      tid = post[0]['tid'];//主题帖id
      pid = post[0]['pid'];//回帖pid
      first = 0;
    }else{
      return F.returnMsg(300, '回帖不存在', 3);
    }
  }

  // 查帖子详情 及 发帖人信息
  var postData = yield mysql.queryOne('select mp.uid,mu.os_type,mu.device_token,mpc.post from mh_post mp LEFT JOIN mh_post_content mpc ON mp.pid=mpc.pid LEFT JOIN mh_user mu ON mp.uid=mu.uid where mp.pid=?',
    [pid]);//发帖人

  var uid = loginStatus.uid;
  var nickName = loginStatus.nickname;
  if (F.isManager(loginStatus.groupid) && !data) {//管理员发帖 并且不包含data 内部调用方式时
    uid = loginStatus.vestuid;
    nickName = loginStatus.vestnickname;
  }

  //判断用户是否为马甲用户
  var isVest=F.isVest(uid);
  console.log('user uid is %s it is  a vest :%s',uid,isVest);

  var isLikeExist = yield MPosts.isLike(pid, uid);
  var gain = 0;

  //回帖点赞
  if(act==3){
    var isSuccess = true;
    if(!isLikeExist){
      //未点赞，对回帖点赞
      isSuccess = yield mysql.query('INSERT ignore INTO mh_likes(tid,pid,uid,first,timeline) VALUES(?,?,?,?,UNIX_TIMESTAMP())',[tid, pid, uid, first]);
      if (isSuccess.affectedRows < 1) {
        return F.returnMsg(400, '点赞失败', 1);
      }
      //更新回帖被点赞数
      yield mysql.query('UPDATE mh_post SET liketimes=liketimes+1 where pid=?',[pid]);
      yield mysql.query('UPDATE mh_user_info SET replybeliked=replybeliked+1 WHERE uid=?', [postData['uid']]);//更新发帖人的回帖被点赞数

      //重新生成用户点赞回帖缓存开始
      key = C.redisPre.user_list;
      key = _.str.sprintf(key, uid, 5);
      temp = yield F.redisCo.EXISTS(key);
      if (temp == 1) {//缓存存在时推进去，不存在时重新生成缓存
        var arr = [];
        arr[0] = key;
        arr.push(F.timestamp());
        arr.push(pid);
        yield F.redisCo.ZADD(arr);
      }
      else {
        yield F.userList(parseInt(uid), 5);
      }
      //重新生成用户点赞回帖缓存结束

      //返回点赞结果
      var postData = yield mysql.queryOne('SELECT liketimes FROM mh_post WHERE pid=?', [pid]);
      return F.returnMsg(200,  '点赞成功', 1,{tid:tid,pid: pid, like: true, liketimes: postData['liketimes']});
    }else{
      return F.returnMsg(200, '亲,您已经点过赞了', 1);
    }
  }

  //取消回帖点赞
  if(act==13){
    if(isLikeExist){
      var result = yield mysql.query('DELETE FROM mh_likes WHERE uid=? AND pid=?', [uid, pid]);
      if (result.affectedRows < 1) {
        return F.returnMsg(400, '取消点赞失败', 1);
      }
      //更新关联数据库统计记录
      var likeTimes = yield mysql.queryOne('SELECT liketimes FROM mh_post WHERE pid=?', [pid]);
      if(parseInt(likeTimes['liketimes'])>0){
        yield mysql.query('UPDATE mh_post SET liketimes=liketimes-1 WHERE pid=? AND liketimes>0',[pid]);
      }

      var rbeliked = yield mysql.queryOne('SELECT replybeliked FROM mh_user_info WHERE uid=?', [postData['uid']]);
      if(parseInt(rbeliked['replybeliked'])>0){
        yield mysql.query('UPDATE mh_user_info SET replybeliked=replybeliked-1 WHERE uid=? AND replybeliked >0', [postData['uid']]);//更新帖子被点赞数
      }
      return F.returnMsg(200, '取消点赞成功', 1);
    }else{
      return F.returnMsg(400, '取消点赞失败', 1);
    }
  }

  if (act == 1 || act == 11) { // 点赞
    var isSuccess = true;
    if (!isLikeExist) {//未点赞
      isSuccess = yield mysql.query('INSERT ignore INTO mh_likes(tid,pid,uid,first,timeline) VALUES(?,?,?,?,UNIX_TIMESTAMP())',
        [tid, pid, uid, first]);
      if (isSuccess.affectedRows < 1) {
        return F.returnMsg(400, '点赞失败', 1);
      }
      yield mysql.query('UPDATE mh_thread SET liketimes=liketimes+1 WHERE tid=?', [tid]);//更新帖子被点赞数

      // logstash流程
      var json = {
        uid: loginStatus.uid,
        tid: tid,
        action: 'like'
      };
      logstash.article(json);

      yield mysql.query('UPDATE mh_user_info SET beliked=beliked+1 WHERE uid=?', [postData['uid']]);//更新发帖人的被点赞数
      //更新发帖人信息开始
      var key = C.redisPre.user_info;
      key = _s.sprintf(key, parseInt(postData['uid']));
      var temp = yield F.redisCo.EXISTS(key);
      if (temp == 1) {
        F.redisClient.HINCRBY(key, 'beliked', 1);//发帖人被点赞+1
      }
      //更新发帖人信息结束

      //更新帖子信息开始
      key = C.redisPre.thread_info;
      key = _s.sprintf(key, parseInt(tid));
      temp = yield F.redisCo.EXISTS(key);
      if (temp == 1) {
        F.redisClient.HINCRBY(key, 'liketimes', 1);//帖子被点赞数+1

        var likeUsers = yield F.redisCo.HGET(key, 'likeusers');
        likeUsers = JSON.parse(likeUsers);
        var face = 0;
        var userData = yield mysql.queryOne('SELECT face FROM mh_user WHERE uid=?', [uid]);
        if (userData) {
          face = userData['face'];
        }
        likeUsers.unshift({uid: uid, face: face});
        var likeUsersLen = likeUsers.length;
        var likeLen = parseInt(C.threadlist.likeLen);
        if (likeUsersLen > likeLen) {
          likeUsers.splice(likeLen, likeUsersLen - likeLen);//点赞用户只存最近N个
        }
        F.redisClient.hmset(key, 'likeusers', JSON.stringify(likeUsers));
      }
      //更新帖子信息结束

      //重新生成用户点赞帖子缓存开始
      key = C.redisPre.user_list;
      key = _.str.sprintf(key, uid, 4);
      temp = yield F.redisCo.EXISTS(key);
      if (temp == 1) {//缓存存在时推进去，不存在时重新生成缓存
        var arr = [];
        arr[0] = key;
        arr.push(F.timestamp());
        arr.push(pid);
        yield F.redisCo.ZADD(arr);
      }
      else {
        yield F.userList(parseInt(uid), 4);
      }
      //重新生成用户点赞帖子缓存结束

      var threadData = yield mysql.queryOne('SELECT liketimes,uliketimes FROM mh_thread WHERE tid=?', [tid]);

      //计算并更新主贴真实用户点赞数据开始
      var uliketimes =parseInt(threadData['uliketimes']);
      //根据uliketimes默认值0,无论点赞用户是否为马甲都要初始化一次之前真实数据并更新uliketimes，初始化之后的点赞只更新真实用户点赞的uliketimes字段
        if(uliketimes==0){
           uliketimes =yield F.getUliketimes(threadData['liketimes'],tid);
          //真实点赞数据更新
          if(uliketimes>0){
            yield mysql.query('UPDATE mh_thread SET uliketimes=? WHERE tid=?', [uliketimes,tid]);
          }
        }else{
          if(!isVest){
            uliketimes=uliketimes+1;
            //真实点赞数据更新
            yield mysql.query('UPDATE mh_thread SET uliketimes=? WHERE tid=?', [uliketimes,tid]);
          }
        }
      //计算并更新主贴真实用户点赞数据结束

      yield F.afterLike();

      // 友盟推送： 帖主不是马甲
      if (!F.isVest(postData['uid'])) {
        var result = yield mysql.queryOne('SELECT pushlike,pushdisturb FROM mh_user_info WHERE uid=?',
          [postData['uid']]);
        // 自己点赞自己不被推送
        if (result && result['pushlike'] == 1 && F.disturb(parseInt(result['pushdisturb'])) && postData['uid'] != uid) {
          var msg = _s.truncate(postData['post'], 27, '...');
          F.umengSendMsg(postData['os_type'], postData['device_token'], 3, {
            nickname: nickName,
            tid: tid,
            msg: msg
          });
        }
      }
      if (!data) {
        gain = yield F.generateIntegralLog(uid, 13, tid);//点赞成功后获得积分
        return F.returnMsg(200, {act: '点赞成功', e: gain}, 4, {
          tid: tid,
          like: true,
          liketimes: parseInt(threadData['liketimes']),
          uliketimes:uliketimes
        });
      }
    }
    else {
      if (!data) {
        var threadData = yield mysql.queryOne('SELECT liketimes,uliketimes FROM mh_thread WHERE tid=?', [tid]);
        return F.returnMsg(200, '亲,您已经点过赞了', 1, {tid: tid, like: true, liketimes: threadData['liketimes'],uliketimes:threadData['uliketimes']});
      }
    }
  }

  if(act==2 || act==12){ // 取消点赞
    var likeTimes = 0;

    if (isLikeExist) {
      var result = yield mysql.query('delete from mh_likes WHERE uid=? and pid=?', [uid, pid]);
      if (result.affectedRows < 1) {
        return F.returnMsg(400, '取消点赞失败', 1);
      }
      var likeTimes = yield mysql.queryOne('SELECT liketimes,uliketimes FROM mh_thread WHERE tid=?', [tid]);
      var uliketimes = parseInt(likeTimes['uliketimes']);
      if (parseInt(likeTimes['liketimes']) > 0) {
        mysql.query('UPDATE mh_thread SET liketimes=liketimes-1 WHERE tid=? and liketimes>0', [tid]);//更新帖子被点赞数

        //同步更新真实用户点赞数
        if(!isVest){
          if(uliketimes>0){
            uliketimes=uliketimes-1;
            mysql.query('UPDATE mh_thread SET uliketimes=uliketimes-1 WHERE tid=?', [tid]);//更新真实用户点赞数
          }
        }

        //更新帖子信息开始
        var key = C.redisPre.thread_info;
        key = _s.sprintf(key, parseInt(tid));
        var temp = yield F.redisCo.EXISTS(key);
        if (temp == 1) {
          F.redisClient.HINCRBY(key, 'liketimes', -1);//帖子被点赞数-1
          var likeUsers = yield F.redisCo.HGET(key, 'likeusers');
          likeUsers = JSON.parse(likeUsers);
          for (var i in likeUsers) {
            if (parseInt(likeUsers[i].uid) == uid) {
              likeUsers.splice(i, 1);
            }
          }
          F.redisClient.hmset(key, 'likeusers', JSON.stringify(likeUsers));
        }
        //更新帖子信息结束
      }
      var beLiked = yield mysql.queryOne('SELECT beliked FROM mh_user_info WHERE uid=?', [postData['uid']]);
      if (parseInt(beLiked['beliked']) > 0) {
        mysql.query('UPDATE mh_user_info SET beliked=beliked-1 WHERE uid=? and beliked>0', [postData['uid']]);//更新发帖人的被点赞数
        //更新发帖人信息开始
        var key = C.redisPre.user_info;
        key = _s.sprintf(key, parseInt(postData['uid']));
        var temp = yield F.redisCo.EXISTS(key);
        if (temp == 1) {
          F.redisClient.HINCRBY(key, 'beliked', -1);//发帖人被点赞数-1
        }
        //更新发帖人信息结束
      }
      //重新生成用户点赞帖子缓存开始
      key = C.redisPre.user_list;
      key = _.str.sprintf(key, uid, 4);
      temp = yield F.redisCo.EXISTS(key);
      if (temp == 1) {
        F.redisClient.ZREM(key, pid);
      }
      //重新生成用户点赞帖子缓存结束
      var threadData = yield mysql.queryOne('SELECT liketimes FROM mh_thread WHERE tid=?', [tid]);
      likeTimes = threadData['liketimes'];
      gain = yield F.generateIntegralLog(uid, 14, tid);//取消点赞成功后获得积分
    }
    else {
      var threadData = yield mysql.queryOne('SELECT liketimes,uliketimes FROM mh_thread WHERE tid=?', [tid]);
      likeTimes = threadData['liketimes'];
      uliketimes = threadData['uliketimes'];
    }
    yield F.afterLike();
    return F.returnMsg(200, {act: '取消点赞成功', e: gain}, 4, {tid: tid, like: false, liketimes: likeTimes,uliketimes:uliketimes});
  }
};
